<template>
  <div class="tool">
    <div class="select_all">
      <div 
      class="checked" 
      :class="{active:isSelectAll}"
      @click="checkedClick"></div>
      <span>全选</span>                                      
    </div>
    <div class="total">
      <span>合计:</span>
      <span>{{totalPrice}}</span>
    </div>
    <div class="settle" @click="calcClick">
      去计算({{checkedLength}})
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
export default {
  name:'CartTool',
 
  computed:{
    ...mapGetters(['cartList']),
    totalPrice(){
      return '￥' + this.cartList.filter(item => {
        return item.isChecked
      }).reduce((preValue,item) => {//preValue每次传入的参数是不固定的, 而是上次执行函数时的结果
        return preValue + item.price*item.count
      },0).toFixed(2)
    },
    checkedLength(){
      return this.cartList.filter(item => item.isChecked
      ).length
    },
    // 全选按钮状态
    isSelectAll(){
      // 当购物车为空时返回false
      if(this.cartList.length === 0){
        return false
      }
      // filter过滤 当购物车中有没有被选中的商品时，要返回false
      // return !(this.cartList.filter(item => !item.isChecked).length)
      // find查找
      return !this.cartList.find(item => !item.isChecked)

      // for(let item of this.cartList){
      //   if(!item.isChecked){
      //     return false
      //   }
      // }
      // return true
    }
  },
  methods:{
    checkedClick(){
      // 点击全选，当全选为true时，购物车的每个商品为false
      if(this.isSelectAll){
        this.cartList.forEach(item => {
          item.isChecked = false
        });
      }else{
        this.cartList.forEach(item => {
          item.isChecked = true
        });
      }
    },
    calcClick(){
      if(this.checkedLength === 0){
        this.$toast.show('请选择购买的商品')
      }
    }
  }
}  
</script>

<style scoped>
.tool{
  position: absolute;
  left:0;
  right: 0;
  bottom: 49px;
  line-height: 40px;
  display: flex;
  font-size: 14px;
  background: #f5f5f5;
}
.tool .select_all{
  width: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-left: 10px;
}
.tool .select_all .checked{
  width: 22px;
  height:22px;
  border-radius: 50%;
  border:2px solid #eee;
  margin-right:5px;
}
.tool .active{
  background-image: url('~assets/img/cart/tick.svg');
  background-repeat: no-repeat;
  background-position: center center;
  background-color:var(--color-tint) ;
  border: none;
}
.tool .total{
  flex:1;
  text-align: center;
}
.tool .settle{
  text-align: center;
  width: 100px;
  color: #fff;
  background: var(--color-tint);
}
</style>